package com.ydd.wrench.server.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cellplus.comm.util.ImpStringUtil;
import com.ydd.wrench.bean.base.User;

/**
 * Cookie公共方法
 * 
 * @author JAQ 2014-08-15
 * 
 */
@Component("cookieUtils")
public class CookieUtils {
  private static transient Logger logger = LoggerFactory.getLogger(CookieUtils.class);

  private static final String SESSION_INFO = "GZQ_BACK_SESSIONINFO";

  private CookieUtils() {}

  /**
   * 通过静态内部类生成单例
   * 
   * @author Administrator
   * 
   */
  private static class SingletonInnerClassInstance {
    private static CookieUtils instance = new CookieUtils();
  }

  public static CookieUtils getInstance() {
    return SingletonInnerClassInstance.instance;
  }

  /**
   * 用户登录标记
   */
  public final static String LOGIN_FLAG = "gongzuoquan.back.info";

  /**
   * 添加登录用户email作为cookies
   * 
   * @param email
   * @param response
   * @return
   */
  public boolean addCookie(String code, HttpServletRequest request) {
    try {
      HttpSession session = request.getSession();
      session.setAttribute(SESSION_INFO, code);
      logger.info("add cookies code=" + code);
    } catch (Exception e) {
      logger.error("", e);
      return false;
    }
    return true;
  }

  /**
   * 退出 移除cookies
   * 
   * @param request
   * @param response
   * @return
   */
  public boolean removeCookie(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    session.invalidate();
    return true;
  }

  /**
   * 获取当前用户cookies值
   * 
   * @param cookies
   * @return
   */
  public String getCookieValue(HttpServletRequest request) {
    HttpSession session = request.getSession();
    Object sessionInfo = session.getAttribute(SESSION_INFO);
    String cookieValue = sessionInfo == null ? null : sessionInfo.toString();
    return cookieValue;
  }

  public String getUserId(HttpServletRequest request) {
    String cookieValue = getCookieValue(request);
    if ( ImpStringUtil.isEmpty(cookieValue) )
    	return "";
    cookieValue = ThreeDes.decrypt(cookieValue);
    if (StringUtils.isNotEmpty(cookieValue)) {
      // userId|deviceType|deviceId|token|lastLoginTime
      String[] decryptValue = cookieValue.split("[|]");
      if (decryptValue.length >= 2) {
        return decryptValue[1];
      }
    }
    return "";
  }
  
  public int getUserType(HttpServletRequest request) {
    String cookieValue = getCookieValue(request);
    if ( ImpStringUtil.isEmpty(cookieValue) )
      return -1;
    cookieValue = ThreeDes.decrypt(cookieValue);
    if (StringUtils.isNotEmpty(cookieValue)) {
      // userId|deviceType|deviceId|token|lastLoginTime
      String[] decryptValue = cookieValue.split("[|]");
      if (decryptValue.length >=3) {
        return (int) Integer.parseInt( decryptValue[2]);
      }
    }
    return -1;
  }
  
  public String getUserOid(HttpServletRequest request){
    String cookieValue = getCookieValue(request);
    if ( ImpStringUtil.isEmpty(cookieValue) )
      return "";
    cookieValue = ThreeDes.decrypt(cookieValue);
    if (StringUtils.isNotEmpty(cookieValue)) {
      // userId|deviceType|deviceId|token|lastLoginTime
      String[] decryptValue = cookieValue.split("[|]");
      if (decryptValue.length >=4) {
        return decryptValue[3];
      }
    }
    return "";
  }

  public String getToken(HttpServletRequest request) {
    String cookieValue = getCookieValue(request);
    if (StringUtils.isNotEmpty(cookieValue)) {
      // userId|deviceType|deviceId|token|lastLoginTime
      String[] decryptValue = cookieValue.split("[|]", 6);
      if (decryptValue.length >= 5) {
        return decryptValue[3];
      }
    }
    return null;
  }

  public String getUserDeviceType(HttpServletRequest request) {
    String cookieValue = getCookieValue(request);
    if (StringUtils.isNotEmpty(cookieValue)) {
      // userId|deviceType|deviceId|token|lastLoginTime
      String[] decryptValue = cookieValue.split("[|]", 6);
      if (decryptValue.length >= 5) {
        return decryptValue[1];
      }
    }
    return null;
  }

  public String getUserDeviceId(HttpServletRequest request) {
    String cookieValue = getCookieValue(request);
    if (StringUtils.isNotEmpty(cookieValue)) {
      // userId|deviceType|deviceId|token|lastLoginTime
      String[] decryptValue = cookieValue.split("[|]", 6);
      if (decryptValue.length >= 5) {
        return decryptValue[2];
      }
    }
    return null;
  }

  public String getCookieOrigValue(User user) {
    // userId|deviceType|deviceId|token|lastLoginTime
    StringBuilder builder = new StringBuilder();
    builder.append( MD5.crypt( user.pwd)).append("|")
        .append(user.userName).append("|").append(user.userType).append("|").append(user.oid);
    return ThreeDes.encrypt(builder.toString());
  }
}
